<?php
namespace translate;

abstract class translate{

    protected $sourceDir;
    protected $createdDir;

    protected $ruleConfig;
    private $config;

    function __construct($config)
    {
        $sourceDir   =  $config['sourceDir'];
        $createdDir  =  $config['createdDir'];

        if(!is_dir($sourceDir)){
            throw new \Exception($sourceDir." 目录不存在 !");
        }
        if(!is_dir($createdDir)){
            mkdir($createdDir);
        }

        $this->sourceDir  = $sourceDir;
        $this->createdDir = $createdDir;
        $this->ruleConfig = $config['rulesConfig'];
        $this->config = $config;
    }

    /**
     * 获取配置项目
     * @param $key
     * @return mixed
     */
    protected function getConfig($key){
        return $this->config[$key];
    }

    /**
     * 获取所有的配置文件
     * @return mixed
     */
    public function getConfigs(){
        return $this->config;
    }

    /**
     * 获取替换规则权限
     * @param $key
     * @return bool
     */
    protected function getRuleConfig($key){
        if(isset($this->ruleConfig[$key])){
            return $this->ruleConfig[$key];
        }
        return false;
    }

    /**
     * 获取内容
     * @param $file
     * @return bool
     */
    protected function getContent($file){
        $ab_path = $this->sourceDir.$file;
        if(!file_exists($ab_path)){
            return false;
        }
        return file_get_contents($ab_path);
    }

    /**
     * 转换数据
     * @param $file
     * @return bool | mixed
     */
    function translate($file){
        if(!$content = $this->getContent($file)){
            return false;
        }

        if($mipContent = $this->_translate($content)){
            $mipFile = $this->getTranslatedAfterFile($file);
            file_put_contents($mipFile,$mipContent);
        }
    }

    /**
     * 获取转换之后的结果目录
     */
    function getTranslatedAfterFile($file){
        $mipFile = $this->createdDir.$file;
        $mipDir  = pathinfo($mipFile,PATHINFO_DIRNAME);
        if(!is_dir($mipDir)){
            @mkdir($mipDir,0777,true);
        }
        return $mipFile;
    }

    /**
     * 数据转换
     * @param $content
     * @return mixed
     */
    function _translate($content){

        foreach($this->getRules() as $rule){

            $content = call_user_func($rule,$content);
        }
        return $content;
    }

    /**
     * 获取转换规则
     * @return array
     */
    function getRules(){
        return [];
    }
}

?>